//
//  NetworkTool.swift
//  weibo001
//
//  Created by ios on 15/11/6.
//  Copyright © 2015年 ios. All rights reserved.
//

import UIKit
import AFNetworking


//http 请求方法枚举
enum CCRequestMethod: String {
      case GET = "GET"
    case POST = "POST"

}

// MARK: - 应用程序信息
private let appKey = "3995771732"
private let appSecret = "c7b253a8381da34eb612a190fee5d100"
private let redirectUrl = "http://www.baidu.com"

//MARK: 单例
class NetworkTool:AFHTTPSessionManager {


    static let sharedTools: NetworkTool = {
    
    let tools = NetworkTool(baseURL: nil)
    
    tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
    return tools
    }()
    

}

//MARK: 授权 URL

extension  NetworkTool {

    
    //计算型熟悉 授权页面
    var oauthURL:NSURL {
    
    let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectUrl)"
        
    return NSURL(string: urlString)!
    }

//  加载 AccessToken
    
    func loadAccessToken(code:String,finished:RequestCallBack) {
    
    let urlString = "https://api.weibo.com/oauth2/access_token"
    
        let params = ["client_id": appKey,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectUrl]
        
        
        request(.POST, URLString: urlString, parameters: params, finished: finished)
    
       // responseSerializer = AFHTTPResponseSerializer()
    }
    
    
}

// MARK: 用户信息
extension NetworkTool {
    func loadUserInfo(uid:String,accessToken:String,finished:RequestCallBack) {
        let urlString = "https://api.weibo.com/2/users/show.json"
        let params = ["uid": uid,
            "access_token": accessToken]
        
        request(.GET, URLString:urlString , parameters: params, finished: finished)
    }
}




//MARK: 封装AFN网络方法


extension NetworkTool {

    typealias RequestCallBack = (result:AnyObject?,error:NSError?)->()
    
//    override func GET(URLString: String, parameters: AnyObject?, success: ((NSURLSessionDataTask, AnyObject) -> Void)?, failure: ((NSURLSessionDataTask, NSError) -> Void)?) -> NSURLSessionDataTask? {
//        code
//    }


    func request(method:CCRequestMethod,URLString:String,parameters:[String:AnyObject]?,finished:RequestCallBack ) {
    
        let success = {(task:NSURLSessionDataTask,result:AnyObject) ->Void in
            
            finished(result: result, error: nil)
        
        }
    
        let failure = {(task:NSURLSessionDataTask,error:NSError) ->Void in
            
            finished(result: nil, error: error)
            
        }

        if method == CCRequestMethod.GET {
        
           GET(URLString, parameters: parameters, success: success, failure: failure)
        
        }else {
        
        POST(URLString, parameters: parameters, success: success, failure: failure)
        
        }
    
    }

    
    
}
















































